package com.mall.controller;

import com.mall.db.domain.JobAndTrigger;
import com.mall.db.service.SchedulerService;
import com.mall.job.BaseJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/sc")
public class SchedulerController extends BaseController<JobAndTrigger> {

    @Resource(name = "schedulerService")
    private SchedulerService ss;

    @Autowired
    private Scheduler scheduler;

    @Override
    public Map<String, Object> find(JobAndTrigger jobAndTrigger) {
        List<JobAndTrigger> list=ss.find();
        return this.findMap(list, list.size());
    }

    @Override
    public Map<String, Object> add(JobAndTrigger jobAndTrigger) {
        Map<String,Object>map=new HashMap<>();
        //启动调度器
        try {
            scheduler.start();
            //构建任务详情
            JobDetail detail= JobBuilder.newJob(getClass(jobAndTrigger.getClassName()).getClass())
                    .withIdentity(jobAndTrigger.getJobName(), jobAndTrigger.jobGroup)
                    .build();
            //cron表达式的构建
            CronScheduleBuilder cron=CronScheduleBuilder.cronSchedule(jobAndTrigger.getCorn());
            //构建新的触发器
            CronTrigger trigger=TriggerBuilder.newTrigger().withIdentity(jobAndTrigger.getTriggerName(), jobAndTrigger.getTriggerGroup())
                    .withSchedule(cron).build();

            //保存且启动
            scheduler.scheduleJob(detail,trigger);
            map.put("is",true);
            map.put("msg", jobAndTrigger.getJobName()+"定时任务构建成功!");
        }catch (Exception e){
            e.printStackTrace();
            map.put("is",false);
            map.put("msg", jobAndTrigger.getJobName()+"定时任务构建失败!");
        }

        return map;
    }

    @Override
    public Map<String, Object> update(JobAndTrigger jobAndTrigger) {
        Map<String, Object>map=new HashMap<>();
       try {
           TriggerKey key=TriggerKey.triggerKey(jobAndTrigger.getTriggerName(), jobAndTrigger.getTriggerGroup());
           //构建cron表达式
           CronScheduleBuilder corn =CronScheduleBuilder.cronSchedule(jobAndTrigger.getCorn());
           //重新构建触发器
           CronTrigger trigger =(CronTrigger) scheduler.getTrigger(key);
           trigger=trigger.getTriggerBuilder()
                   .withIdentity(key)
                   .withSchedule(corn).build();
           map.put("is",true);
           map.put("msg","更新定时任务成功");
       }catch (Exception e){
           e.printStackTrace();
           map.put("is",false);
           map.put("msg","更新定时任务失败");
       }
        return map;
    }

    public BaseJob getClass(String className){
        try {
            Class<?>c=Class.forName(className);
            return (BaseJob) c.newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/runOne")
    public Map<String,Object> runOne(JobAndTrigger s){//JobAndTrigger
        Map<String,Object> map = new HashMap<>();
        if("ACQUIRED".equals(s.getState())){
            map.put("msg","任务正在执行，无法再执行一次....");
            return map;
        }

        JobDetail job = JobBuilder.newJob(getClass(s.getClassName()).getClass()).build();

        //指定一个时间触发，不重复
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity("oneTrigger","oneTriggerGroup")
                //.startAt(new Date()) //指定一个时间执行
                .startNow()//立即执行
                .build();
        try {
            scheduler.scheduleJob(job,trigger);
            map.put("msg", "任务开始执行且执行一次");
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
}
